package top.lyc829.zzl_android.ui.add;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.ScreenUtils;
import com.xuexiang.citypicker.adapter.OnLocationListener;
import com.xuexiang.citypicker.model.LocateState;
import com.xuexiang.citypicker.model.LocatedCity;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityAddDynamicBinding;
import top.lyc829.zzl_android.logic.adapter.GridImageAdapter;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.util.GlideEngine;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;

public class AddDynamicActivity extends AppCompatActivity {

    ActivityAddDynamicBinding binding;
    private GridImageAdapter mAdapter;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = null;

    public AMapLocationClientOption mLocationOption = null;

    String location = "";

    MaterialDialog loadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAddDynamicBinding.inflate((getLayoutInflater()));
        setContentView(binding.getRoot());

        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                3, GridLayoutManager.VERTICAL, false);
        binding.recycler.setLayoutManager(manager);

        binding.recycler.addItemDecoration(new GridSpacingItemDecoration(3,
                ScreenUtils.dip2px(this, 8), false));




        mAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mAdapter.setSelectMax(9);
        binding.recycler.setAdapter(mAdapter);

        binding.scbIsPublic.setChecked(true);   // 默认公开
        clickListener();

        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {

                if (aMapLocation !=null && aMapLocation.getErrorCode() == 0) {
                    Utils.Sout( "地址" + aMapLocation.getAddress());
                    String city = aMapLocation.getCity().substring(0, aMapLocation.getCity().length() - 1);
                    location = city;
                    binding.txtLocation.setText(city);
                    binding.txtLocation.setVisibility(View.VISIBLE);
                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);

    }

    // 点击事件
    private void clickListener() {

        binding.mTitleBarAddDynamic.setLeftClickListener(v -> finish());

        mAdapter.setOnItemClickListener((v, position) -> {
            List<LocalMedia> selectList = mAdapter.getData();
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                PictureSelector.create(this)
                        .themeStyle(R.style.picture_default_style) // xml设置主题
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                        .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                        .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(position, selectList);
            }
        });

        binding.textIsPublic.setOnClickListener(v -> binding.scbIsPublic.toggle());
        binding.txtIsShowLocation.setOnClickListener(v -> binding.scbIsShowLocation.toggle());
        binding.scbIsShowLocation.setOnCheckedChangeListener((checkBox, isChecked) -> {
            if (isChecked) {
                XXPermissions.with(this)
                        .permission(Permission.ACCESS_FINE_LOCATION)
                        .permission(Permission.ACCESS_COARSE_LOCATION)
                        .request(new OnPermissionCallback() {

                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                if (all) {
                                    startLocation();
                                } else {
                                    Utils.showToast("请授权定位");
                                    binding.scbIsShowLocation.setChecked(false);
                                }
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                Utils.showToast("请授权定位");
                                binding.scbIsShowLocation.setChecked(false);
                            }
                        });
            } else {
                binding.txtLocation.setVisibility(View.INVISIBLE);
            }
        });

        binding.btnDynamicSend.setOnClickListener(v -> {
            boolean isPublic = binding.scbIsPublic.isChecked();
            boolean isShowLocation = binding.scbIsShowLocation.isChecked();

            String text = binding.textDynamic.getContentText().trim();
            if (Utils.isStringEmpty(text)) {
                Utils.showToast("内容不能为空");
                return;
            }

            // 实例化加载框
            loadingDialog = new MaterialDialog.Builder(this)
                    .customView(R.layout.dialog_loading_layout, true)
                    .cancelable(false)
                    .build();
            loadingDialog.show();
            uploadDynamic(text, isShowLocation ? location : "", isPublic);
        });



        // TODO: 长按图片进行拖动
        mAdapter.setItemLongClickListener((holder, position, v) -> {});

    }

    private void startLocation() {
        mLocationClient.startLocation();
    }

    private void uploadDynamic(String text,String location, boolean isPublic) {

        List<LocalMedia> mediaList = mAdapter.getData();
        List<File> fileList  = new ArrayList<>();
        for (LocalMedia media : mediaList) {
            fileList.add(new File(media.getCompressPath()));
        }

        Map<String, String> map = new HashMap<>();
        map.put("user_id", String.valueOf(Utils.getUserId()));
        map.put("text", text);
        map.put("location", location);
        map.put("is_public", isPublic ? "1" : "0");

        List<Pair<String, File>> photos = new ArrayList<>();
        for (File file : fileList) {
            photos.add(new Pair<>("img", file));
        }
        HttpUtil.getInstance(this).sendMultipart(Url.ADD_DYNAMIC, map, photos, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resultStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        Utils.showToast("发布成功");
                        loadingDialog.dismiss();
                        finish();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                    loadingDialog.dismiss();
                }

            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
                loadingDialog.dismiss();
            }
        });


//        Network.sendDynamic(Utils.getUserId(), text, location, isPublic, new HttpUtil.MyCallback() {
//            @Override
//            public void success(Response res) throws IOException {
//                String resultStr = res.body().string();
//
//                ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
//
//                if (resultBean.getCode().equals("200")) {
//                    // TODO: 上传图片
//
//                    runOnUiThread(() -> {
//                        Utils.showToast("发布成功");
//                        AddDynamicActivity.this.finish();
//                    });
//                } else {
//                    failed(new IOException(resultBean.getMsg()));
//                }
//            }
//
//            @Override
//            public void failed(IOException e) {
//
//            }
//        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(AddDynamicActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .isMaxSelectEnabledMask(true)// 选择数到了最大阀值列表是否启用蒙层效果
                    .selectionData(new WeakReference<>(mAdapter).get().getData())
                    .maxSelectNum(9)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    //.closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 关闭在AndroidQ下获取图片或视频宽高相反自动转换
                    .imageSpanCount(3)// 每行显示个数
                    .isCompress(true)
                    .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                    .closeAndroidQChangeWH(true)//如果图片有旋转角度则对换宽高,默认为true
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .synOrAsy(false)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> result) {
                            // 结果回调
                            WeakReference<GridImageAdapter> mAdapterWeakReference= new WeakReference<>(mAdapter);
                            mAdapterWeakReference.get().setList(result);
                            mAdapterWeakReference.get().notifyDataSetChanged();
                        }

                        @Override
                        public void onCancel() {
                            // 取消
                        }
                    });

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();
        mLocationClient.onDestroy();
        loadingDialog = null;
    }
}